package servlet;

import biz.UsersBiz;
import biz.impl.UsersBizImpl;
import org.apache.ibatis.session.SqlSessionFactory;
import org.example.bean.UsersInfo;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/users")
public class UsersServlet extends HttpServlet {
    private UsersBiz ub;

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String type = req.getParameter("type");
        if ("login".equals(type)) {
            login(req, resp);
        } else if ("zhu".equals(type)) {
            zhu(req, resp);
        }
    }

    protected void login(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        String phone = request.getParameter("phone");
        String pass = request.getParameter("pass");
        HttpSession session = request.getSession();
        ServletContext application = session.getServletContext();
        SqlSessionFactory ssf = (SqlSessionFactory) application.getAttribute("SQL_SESSION_FACTORY");
        ub = new UsersBizImpl(ssf.openSession());
        UsersInfo ui = ub.findUsersByPhone(phone, pass);
        if (null == ui) {
            session.setAttribute("ERROR_MGS", "账号或密码错误");
        } else {
            session.setAttribute("USER_INFO", ui);
        }
        response.sendRedirect("index.jsp");
    }

    protected void zhu(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        HttpSession session = request.getSession();
        session.removeAttribute("USER_INFO");
        response.sendRedirect("index.jsp");
    }
}